#include "stdafx.h"
#include "Class2MidValueOpt.h"

#include "conio.h"

Class2MidValueOpt::Class2MidValueOpt()
{
	picID = IDB_CLASS2_MIDVALUE;

	resetBitMap();
}

Class2MidValueOpt::~Class2MidValueOpt()
{

}


COLORREF Class2MidValueOpt::getAvgColor(CImage *image, int x, int y, int maxX, int maxY)
{
	COLORREF color;
	long avg = 0;
	int width, height;
	int i, j;

	for (i = 0; i < 3; i++) {
		for (j = 0; j < 3; j++) {
			width = x - 1 + i;
			height = y - 1 + j;

			if (width < 0) {
				width = 0;
			}
			else if (width >= maxX) {
				width = maxX - 1;
			}

			if (height < 0) {
				height = 0;
			}
			else if (height >= maxY) {
				height = maxY - 1;
			}
			
			color = image->GetPixel(width, height);
			avg += (color & 0xFF);
//			cprintf("%x\n", avg);
		}
	}

	avg = (avg / 9) & 0xFF;
	color = (avg << 16) | (avg << 8) | avg;
//	cprintf("%x\n", color);

	return color;
}

void Class2MidValueOpt::drawPics(CDC* pDC) 
{
	CImage srcimage, destimage;
	COLORREF color;
	BITMAP srcInfo;

	srcBitMap.GetBitmap(&srcInfo);


//	destBitMap.Attach(CopyBitmap(srcBitMap));
	CopyBitmap(&srcBitMap, &destBitMap);

	cbitMapToImage(&srcimage, &srcBitMap);
	cbitMapToImage(&destimage, &destBitMap);

	int width, height;

	for (width = 0; width < srcInfo.bmWidth - 1; width++) {
		for (height = 0; height < srcInfo.bmHeight - 1; height++) {
			color = getAvgColor(&srcimage, width, height, srcInfo.bmWidth, srcInfo.bmHeight);
			destimage.SetPixel(width, height, color);
		}
	}

	clearRect(pDC, 800, 800);

	CDC cdc;
	cdc.CreateCompatibleDC(pDC);
	cdc.SelectObject(&srcBitMap);
	pDC->BitBlt(30, 20, 180, 180, &cdc, 1, 1, SRCCOPY);

	cdc.SelectObject(&destBitMap);
	pDC->BitBlt(330, 20, 180, 180, &cdc, 1, 1, SRCCOPY);
}

